package com.io.smartappframe.mvc.activity

import android.content.ContentUris
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.view.View
import com.alibaba.sdk.android.oss.ClientException
import com.alibaba.sdk.android.oss.ServiceException
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback
import com.alibaba.sdk.android.oss.model.PutObjectRequest
import com.alibaba.sdk.android.oss.model.PutObjectResult
import com.io.base.mvc.BaseActivityMVC
import com.io.commonlib.helper.CommonDeviceHelper
import com.io.commonlib.helper.DateHelper
import com.io.commonlib.helper.FileHelper
import com.io.commonlib.helper.LogHelper
import com.io.smartappframe.R
import com.io.smartappframe.common.AppConstants
import com.io.smartappframe.databinding.ActivityImageGroupViewBinding
import com.io.thirdparties.aliyun.AliyunOSSHelper
import com.io.viewgroup.image.ImageGroupView
import com.io.viewgroup.image.interfaces.IOnClickPhotoAlbumListener
import com.io.viewgroup.image.interfaces.IOnClickTakePhotoListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * Description:ImageGroupView的测试类
 * 2021-03-22 11:24
 * @author LiuMin
 */
class ImageGroupViewActivity : BaseActivityMVC<ActivityImageGroupViewBinding>(),
    View.OnClickListener,
    IOnClickTakePhotoListener, IOnClickPhotoAlbumListener,
    OSSCompletedCallback<PutObjectRequest, PutObjectResult> {

    private lateinit var filePath: String
    private lateinit var aliyunFilePath: String
    private lateinit var mCurrentImageGroupView: ImageGroupView

    override fun initView(savedInstanceState: Bundle?): ActivityImageGroupViewBinding {
        return ActivityImageGroupViewBinding.inflate(layoutInflater)
    }

    override fun initData(savedInstanceState: Bundle?) {
        mViewBinding.header.tvTitle.setText("测试ImageGroupView")
        mViewBinding.header.ivToolbarBack.setOnClickListener(this)
        //设置数据源
        var list = mutableListOf<String>()
        list.add("http://soonsmart.keji.io/IOConstruction/20210302/10/1614652761216-261.png")
        list.add("http://soonsmart.keji.io/IOConstruction/20210311/17/1615455419879-259.png")
        list.add("http://soonsmart.keji.io/IOConstruction/20210302/13/1614664014468-259.png")
        list.add("http://soonsmart.keji.io/IOConstruction/20210302/13/1614664028364-259.png")
        mViewBinding.imageGroupView.setData(list)
        //事件绑定
        mViewBinding.imageGroupView.setOnClickTakePhotoListener(this)
        mViewBinding.imageGroupView.setOnClickPhotoAlbumListener(this)

        filePath = "${getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.path}/temp.png"
        AliyunOSSHelper.setOSSCompletedCallback(this)
    }

    override fun onClick(v: View?) {
        v?.let {
            if (it.id == R.id.iv_toolbar_back) {
                finish()
            }
        }
    }

    override fun onClickTakePhoto(imageGroupView: ImageGroupView) {
        mCurrentImageGroupView = imageGroupView
        CommonDeviceHelper().openCameraAndSaveImage(
            this,
            filePath,
            AppConstants.TAKE_PHOTO_REQUEST_CODE
        )
    }

    override fun onClickPhotoAlbum(imageGroupView: ImageGroupView) {
        mCurrentImageGroupView = imageGroupView
        CommonDeviceHelper().getPhotoFromSysAlbum(this, AppConstants.PHOTO_ALBUM_REQUEST_CODE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            if (requestCode == AppConstants.TAKE_PHOTO_REQUEST_CODE) {
                progressDialog.setLoadingContent(R.string.image_uploading_msg)
                progressDialog.show()
                if (filePath.isNotEmpty() && FileHelper().fileIsExists(filePath)) {
                    aliyunFilePath = getNewImagePath()
                    AliyunOSSHelper.uploadFileToAliOss(filePath, aliyunFilePath)
                } else {
                    progressDialog.hide()
                }
            } else if (requestCode == AppConstants.PHOTO_ALBUM_REQUEST_CODE) {
                progressDialog.setLoadingContent(R.string.image_uploading_msg)
                progressDialog.show()
                data?.let {
                    getImagePathFromIntent(it)
                    val imagePath = getImagePathFromIntent(data)
                    if (imagePath.isNotEmpty() && FileHelper().fileIsExists(imagePath)) {
                        aliyunFilePath = getNewImagePath()
                        AliyunOSSHelper.uploadFileToAliOss(imagePath, aliyunFilePath)
                    } else {
                        progressDialog.hide()
                    }
                } ?: let {
                    progressDialog.hide()
                }
            }
        }
    }

    /**
     * 从系统返回的Intent中拿到图片路径
     * 4.4版本后 调用系统相机返回的不在是真实的uri 而是经过封装过后的uri，
     * 所以要对其进行数据解析
     */
    private fun getImagePathFromIntent(data: Intent): String {
        var imagePath = ""
        val uri = data.data
        uri?.let {
            if (DocumentsContract.isDocumentUri(this, uri)) {
                //如果是document类型的uri 则通过id进行解析处理
                val docId = DocumentsContract.getDocumentId(uri)
                if ("com.android.providers.media.documents".equals(uri.authority)) {
                    //解析出数字格式id
                    val id = docId.split(":")[1]
                    val selection = MediaStore.Images.Media._ID + "=" + id
                    imagePath =
                        getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection)
                } else if ("com.android.providers.downloads.documents".equals(uri.authority)) {
                    val contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"),
                        docId.toLong()
                    )
                    imagePath = getImagePath(contentUri, null)
                }
            } else if("content".equals(uri.scheme)){
                //如果不是document类型的uri，则使用普通的方式处理
                imagePath = getImagePath(uri, null)
            }
        }
        return imagePath
    }

    /**
     * 通过 uri seletion选择来获取图片的真实uri
     */
    private fun getImagePath(uri: Uri, selection: String?): String {
        var path = ""
        val cursor = contentResolver.query(uri, null, selection, null, null)
        cursor?.let {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))
            }
            cursor.close()
        }
        return path
    }

    /**
     * 获取文件在阿里云服务器上的路径
     */
    private fun getNewImagePath(): String {
        val fileSuffix = FileHelper().getFileSuffix(filePath)
        val timeStr = DateHelper.getNowDateTimeStr("yyyyMMdd")
        return "${AppConstants.ALIYUN_OBJECT_KEY}${timeStr}/${System.currentTimeMillis()}${fileSuffix}"
    }

    //region 阿里云图片上传的回调方法
    /**
     * 图片上传成功
     */
    override fun onSuccess(request: PutObjectRequest?, result: PutObjectResult?) {
        request?.let {
            //先删除本地文件
            val localPath = request.uploadFilePath
            FileHelper().deleteFile(localPath)
            LogHelper.d(TAG, "图片上传成功，${aliyunFilePath}")
            scope.launch(Dispatchers.Main) {
                progressDialog.dismiss()
                mCurrentImageGroupView.addSingleImage("${AppConstants.Aliyun_Path}${aliyunFilePath}")
            }
        }
    }

    /**
     * 图片上传失败
     */
    override fun onFailure(
        request: PutObjectRequest?,
        clientException: ClientException?,
        serviceException: ServiceException?
    ) {
        LogHelper.d(TAG, "onFailure--图片压缩失败")
    }
    //endregion

    override fun onDestroy() {
        super.onDestroy()
        if (progressDialog.isShowing) {
            progressDialog.dismiss()
        }
        AliyunOSSHelper.setOSSCompletedCallback(null)
    }
}